import { Injectable } from '@nestjs/common';
import { chunk, find } from 'lodash';
import { Author, Post } from '../models/models';
import { FakeSource } from '../fakesource/fakesource';

@Injectable()
export class AuthorsService {
    fakeSource = FakeSource.getInstance();

    async authorList(pageIdx: number, pageCount: number): Promise<Author[]> {
        const { authors } = this.fakeSource;

        return new Promise((resolve, reject) => {
            resolve(chunk(authors, pageCount)[pageIdx]);
        });
    }

    async findAuthorById(id: number): Promise<Author> {
        const { authors } = this.fakeSource;

        return new Promise((resolve, reject) => {
            const author = find(authors, (item) => item.id === id);
            resolve(author);
        });
    }

    async findAuthorByPostId(postId: number): Promise<Author> {
        const { posts } = this.fakeSource;
        return new Promise(async (resolve, reject) => {
            const post = find(posts, (item: Post) => item.id = postId) as Post;
            const author = await this.findAuthorById(post.author.id);
            resolve(author);
        });
    }
}